package me.zhengjie.modules.system.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.modules.system.domain.vo.ChatMessage;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.*;

@Controller
public class ChatController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private RedisUtils redisTemplate;

    @AnonymousAccess
    @MessageMapping("/chat.sendMessage")
    public void sendMessage(@Payload ChatMessage chatMessage, Principal principal) {

        // 设置发送者（如果是客服发送的消息）
        if (principal != null) {
            chatMessage.setSender(principal.getName());
        }
        saveLog(chatMessage);
        // 如果接收者是"SUPPORT"，表示客户发给客服的消息
        if ("SUPPORT".equals(chatMessage.getRecipient())) {
            // 发送给所有客服（广播）
            messagingTemplate.convertAndSend("/queue/support", chatMessage);
            // 或者发送给特定客服（点对点）
            // messagingTemplate.convertAndSendToUser("specificSupport", "/queue/reply", chatMessage);
            chatMessage.getRecipient();
        }
        // 如果有特定接收者，表示客服发给客户的消息
        else if (chatMessage.getRecipient() != null && !chatMessage.getRecipient().isEmpty()) {
            messagingTemplate.convertAndSendToUser(
                    chatMessage.getRecipient(),
                    "/queue/messages",
                    chatMessage
            );
        }
    }

    public void saveLog(ChatMessage chatMessage){
        if ("SUPPORT".equals(chatMessage.getRecipient())) {
            List<Map<String, Object>> senderList = (List<Map<String, Object>>) redisTemplate.get("ws:session:"+chatMessage.getSender());
            Map sendMsg = new HashMap<String, Object>();
            sendMsg.put("content", chatMessage.getContent());
            sendMsg.put("sender", chatMessage.getSender());
            sendMsg.put("recipient", chatMessage.getRecipient());
            sendMsg.put("time", DateUtil.localDateTimeFormatyMdHms(LocalDateTime.now()));
            senderList.add(sendMsg);
            redisTemplate.set("ws:session:"+chatMessage.getSender(), senderList, 600);
        }else{
            List<Map<String, Object>> senderList = (List<Map<String, Object>>) redisTemplate.get("ws:session:"+chatMessage.getRecipient());
            Map sendMsg = new HashMap<String, Object>();
            sendMsg.put("content", chatMessage.getContent());
            sendMsg.put("sender", chatMessage.getSender());
            sendMsg.put("recipient", chatMessage.getRecipient());
            sendMsg.put("time", DateUtil.localDateTimeFormatyMdHms(LocalDateTime.now()));
            senderList.add(sendMsg);
            redisTemplate.set("ws:session:"+chatMessage.getRecipient(), senderList, 600);
        }
    }
    @AnonymousAccess
    @MessageMapping("/chat.addUser")
    @SendTo("/topic/public")
    public ChatMessage addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
        // 将用户名存入WebSocket会话
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        // 如果是客服连接，添加特殊标识
        if (chatMessage.getSender().startsWith("客服_")) {
            headerAccessor.getSessionAttributes().put("role", "SUPPORT");
        }
        List<Map<String, Object>> listMap = new ArrayList<>();
        redisTemplate.set("ws:session:"+chatMessage.getSender(), listMap, 600);
        return chatMessage;
    }

    /**
     * 通过用户ID 获取聊天记录
     * @param sendUser
     * @return
     */
    @AnonymousGetMapping("wsgetUserLog")
    @ResponseBody
    public Object getLog(String sendUser){
        List<Map<String, Object>> senderList = (List<Map<String, Object>>) redisTemplate.get("ws:session:"+sendUser);
        return senderList;
    }

}
